package com.feicheng.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.base.common.DaoConstant;
import com.feicheng.base.exception.SystemException;
import com.feicheng.base.result.Result;
import com.feicheng.entity.User;
import com.feicheng.entity.Warehouse;
import com.feicheng.entity.WarehouseStore;
import com.feicheng.model.UserAndWarehouse;
import com.feicheng.model.WarehouseInfo;
import com.feicheng.model.WarehouseWithStore;
import com.feicheng.model.WarehouseWithUser;
import com.feicheng.service.IUserService;
import com.feicheng.service.IWarehouseService;
import com.feicheng.service.IWarehouseStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hao.zhang
 * @since 2022-07-04
 */
@RestController
@RequestMapping("/warehouse")
public class WarehouseController {

    /* 注入IWarehouseService*/
    @Autowired
    IWarehouseService iWarehouseService;

    /* 注入IWarehouseStoreService*/
    @Autowired
    IWarehouseStoreService iWarehouseStoreService;

    // 将用户表的service自动注入
    @Autowired
    IUserService iUserService;
    /**
     * 通过查询条件查询仓库列表，分页
     * @autor lu.yu
     * @param current
     * @param size
     * @param userAndWarehouse
     * @return
     */
    @PostMapping("/page/g")
    public Result select(@RequestParam(defaultValue = "1") Integer current,
                         @RequestParam(defaultValue = "10") Integer size,
                         @RequestBody UserAndWarehouse userAndWarehouse){

        // 构建查询条件
        QueryWrapper<UserAndWarehouse> userAndWarehouseQueryWrapper
                = new QueryWrapper<UserAndWarehouse>();

        // 如果门店id不是空把门店id加入查询的条件中
        if (null != userAndWarehouse.getStoreId()){
            userAndWarehouseQueryWrapper
                    .eq(DaoConstant.MODEL.USER_AND_WAREHOUSE.STORE_ID,userAndWarehouse.getStoreId());
        }

        // 如果仓库名称不是空把仓库名称加入查询的条件中
        if (StringUtils.hasLength(userAndWarehouse.getWarehouseName())){
            userAndWarehouseQueryWrapper
                    .like(DaoConstant.WAREHOUSE.WAREHOUSE_NAME,
                    userAndWarehouse.getWarehouseName());
        }

        // 如果仓库名状态不是空把仓库状态加入查询的条件中
        if (null != userAndWarehouse.getState()){
            userAndWarehouseQueryWrapper
                    .eq(DaoConstant.WAREHOUSE.STATE,
                    userAndWarehouse.getState());
        }

        // 如果地址不是空把地址加入查询的条件中
        if (StringUtils.hasLength(userAndWarehouse.getAddress())){
            userAndWarehouseQueryWrapper
                    .like(DaoConstant.WAREHOUSE.ADDRESS,
                    userAndWarehouse.getAddress());
        }

        // 如果管理者姓名不是空把管理者姓名加入查询的条件中
        if (StringUtils.hasLength(userAndWarehouse.getUserName())){
            userAndWarehouseQueryWrapper
                    .like(DaoConstant.MODEL.USER_AND_WAREHOUSE.USER_NAME,
                    userAndWarehouse.getUserName());
        }

        // 创建分页查询
        Page<UserAndWarehouse> pageInfo = new Page<UserAndWarehouse>(current, size);

        // 返回查询结果
        return Result.success(iWarehouseService
                .getByPage(pageInfo,userAndWarehouseQueryWrapper));

    }

    /**
     * 仓库新增接口
     * @param warehouseWithStore 仓库信息
     * @autor zhengnan.fu
     * @return
     */
    @PostMapping("/info")
    @Transactional
    public Result addWarehouse(@RequestBody WarehouseWithStore warehouseWithStore) {

        // 仓库名称没有传的时候
        if (!StringUtils.hasLength(warehouseWithStore.getWarehouseName())) {
            throw new SystemException("仓库名称不能为空");
        }

        // 仓库地址没有传的时候
        if (!StringUtils.hasLength(warehouseWithStore.getAddress())) {
            throw new SystemException("仓库地址不能为空");
        }

        // 仓库状态没有传的时候
        if (null == warehouseWithStore.getState()) {
            throw new SystemException("仓库状态不能为空");
        }

        // 管理员ID没有传的时候
        if (null == warehouseWithStore.getUserId()) {
            throw new SystemException("管理员不能为空");
        }

        // 设置d_flg默认值为False
        warehouseWithStore.setDFlg(Boolean.FALSE);

        // 新增仓库表
        iWarehouseService.save(warehouseWithStore);

        // 创建中间表对象
        WarehouseStore warehouseStore = new WarehouseStore();

        // 把门店ID存入中间表
        warehouseStore.setStoreId(warehouseWithStore.getStoreId());

        // 把仓库ID存入中间表
        warehouseStore.setWarehouseId(warehouseWithStore.getWarehouseId());

        // 新增中间表
        iWarehouseStoreService.save(warehouseStore);

        return Result.success(warehouseWithStore);
    }

    /**
     * 仓库下拉查询
     *
     * @param storeId 门店编号
     * @author peiwen.song
     * @since 2022-07-05
     * @return
     */
    @PostMapping("/info/all/g")
    public Result selectWarehouse(
            @RequestParam Integer storeId
    ) {
        //判断门店编号（storeId）是否为空
        if (null == storeId) {

            //TODO
            throw new SystemException("未接取到门店编号");
        }

        //根据门店编号（storeId）查询，建立查询条件
        QueryWrapper<WarehouseStore> warehouseStoreQueryWrapper
                = new QueryWrapper<>();

        warehouseStoreQueryWrapper
                .select(DaoConstant.WAREHOUSE.WAREHOUSEID)
                .in(DaoConstant.WAREHOUSE.STOREID,storeId);

        // 根据条件查询仓库编号（selWarehouseIds）
        List<WarehouseStore> selWarehouseIds
                = iWarehouseStoreService.list(warehouseStoreQueryWrapper);

        //建立新集合（warehouseIds）
        List<Integer> warehouseIds = new ArrayList<>();

        //存储编号（selWarehouseIds）
        for (WarehouseStore warehouseStore:selWarehouseIds) {

            warehouseIds.add(warehouseStore.getWarehouseId());
        }

        //根据仓库编号（warehouseIds）查询仓库信息并返回
        return Result.success(iWarehouseService.listByIds(warehouseIds));
    }

    /**
     *
     * @param warehouseInfo
     * @author yu.xiu
     * @since 2022-07-05
     * @return
     */

    // 修改仓库信息
    @PutMapping("/info")
    public Result updateinfo(
            @RequestBody WarehouseInfo warehouseInfo){

        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 查用户id条件用户名等于前端传的用户名
        queryWrapper.select(
                DaoConstant.USER.USERID).eq(DaoConstant.USER.USERNAME,
                warehouseInfo.getUserName());

        // 查用户id
        List<User> list = iUserService.list(queryWrapper);

        // 判断是否能真正得到用户id
        if(0 == list.size()) {

            // 得不到报异常
            //TODO
            throw  new SystemException("用户名输入错误");
        }

        // 将warehouseInfo装入Warehouse 创建一个Warehouse对象
        Warehouse warehouse = new Warehouse();

        // 将前端传的仓库名装入Warehouse
        // 判断仓库名是否为空
        if (StringUtils.hasLength(warehouseInfo.getWarehouseName())) {

            // 不为空修改
            warehouse.setWarehouseName(warehouseInfo.getWarehouseName());
        }else {

            // 若仓库名为空则抛出异常
            //TODO
            throw  new SystemException("仓库名不能为空");
        }

        // 将前端传的地址装入Warehouse 判断地址是否为空
        if (StringUtils.hasLength(warehouseInfo.getAddress())) {

            // 若不为空修改
            warehouse.setAddress(warehouseInfo.getAddress());
        }else {

            // 为空抛出异常
            //TODO
            throw  new SystemException("地址不能为空");
        }

        // 将前端传的状态装入Warehouse
        warehouse.setState(warehouseInfo.getState());

        // 将前用户id装入Warehouse
        warehouse.setUserId(list.get(0).getUserId());

        // 修改仓库信息
        UpdateWrapper<Warehouse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(
                DaoConstant.WAREHOUSE.WAREHOUSEID,
                warehouseInfo.getWarehouseId());

        // 返回修改状态
        return Result.success(
                iWarehouseService.update(warehouse, updateWrapper));

    }

    /**
     * 根据仓库编号逻辑删除仓库信息接口
     * @param warehouse 仓库信息
     * @author yue.guo
     * @return true/false
     */

    @DeleteMapping("/info")
    public Result updateDflgByWarehouseId(@RequestBody Warehouse warehouse){

        /*构建方法*/
        UpdateWrapper<Warehouse> updateWrapper = new UpdateWrapper<>();

        /*根据仓库id逻辑删除*/
        updateWrapper.eq(DaoConstant.WAREHOUSE.WAREHOUSE_ID,warehouse.getWarehouseId()).set(DaoConstant.WAREHOUSE.D_FLG,1);

        /*返回结果*/
        return Result.success(iWarehouseService.update(warehouse,updateWrapper));

    }

    /**
     * 仓库信息详细查询
     * @param warehouseId 仓库主键
     * @author bo.wei
     * @return
     */
    @PostMapping("/info/g")
    public Result selectWarehouseOne(Integer warehouseId){

        /* 通过仓库编号取出仓库数据 */
        Warehouse warehouse = iWarehouseService.getById(warehouseId);

        /* 实例化一个仓库详情model */
        WarehouseWithUser warehouseWithUser = new WarehouseWithUser();

        /* 向仓库详情里插入仓库编号 */
        warehouseWithUser.setWarehouseId(warehouse.getWarehouseId());

        /* 向仓库详情里插入仓库名称 */
        warehouseWithUser.setWarehouseName(warehouse.getWarehouseName());

        /* 向仓库详情里插入仓库地址 */
        warehouseWithUser.setAddress(warehouse.getAddress());

        /* 向仓库详情里插入仓库状态 */
        warehouseWithUser.setState(warehouse.getState());

        /* 向仓库详情里插入仓库删除状态 */
        warehouseWithUser.setDFlg(warehouse.getDFlg());

        /* 向仓库详情里插入管理员主键 */
        warehouseWithUser.setUserId(warehouse.getUserId());

        /* 通过管理员主键寻找管理员信息 */
        User user = iUserService.getById(warehouse.getUserId());

        /* 向仓库详情里插入管理员姓名 */
        warehouseWithUser.setUserName(user.getUserName());

        /* 向仓库详情里插入管理员电话 */
        warehouseWithUser.setTelephone(user.getTelephone());

        /* 通过userid的storeid查此店铺下所有员工 */
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        /* 构造条件 */
        userQueryWrapper.eq(DaoConstant.STORE_USER.STORE_ID, user.getStoreId());

        /* 查出所有仓库管理员 */
        List<User> userList = iUserService.list(userQueryWrapper);

        /* 向仓库详情里放所有管理员信息 */
        warehouseWithUser.setUserList(userList);

        /* 返回仓库详情信息 */
        return Result.success(warehouseWithUser);
    }

}







